import React, { useEffect, useState, useCallback, useRef } from "react";
import { Card, Checkbox, Button, Image, Tag, Toast, Modal, Radio, ImageViewer, Dialog, ErrorBlock } from "antd-mobile";
import debounce from "lodash.debounce";
import EmptyBlock from "@/components/emptyBlock";

import "./index.css";
import cartApi from "@/api/iap/cart";
import orderApi from "@/api/iap/order";
import { useNavigate, useSearchParams } from 'react-router-dom';
import ChooseAddress from "@/components/chooseAddress";


export default function ShopCar() {
    const navigate = useNavigate();
    const [goodsIds, setGoodsIds] = useState([]);
    const [curActId, setCurActId] = useState(0);
    const [totalPrice, setTotalPrice] = useState(0);
    const [cartData, setCartData] = useState([]);
    const [loadingMap, setLoadingMap] = useState({});
    const [loadingCreate, setLoadingCreate] = useState(false);
    const [removeDialogVisible, setRemoveDialogVisible] = useState(false);
    const chooseAddressRef = useRef(null);
    // 关键：增加一个标记，记录initFromAddress是否已执行
    const [isFirstLoad, setIsFirstLoad] = useState(true);
    const [initExecuted, setInitExecuted] = useState(false); // 新增：标记初始化逻辑是否已执行
    const [pickUpStation, setPickUpStation] = useState(false); // 新增：标记初始化逻辑是否已执行
    const [removeData, setRemoveData] = useState({
        id: '',
        dialogVisible: false,
        loading: false
    });
    const [imageData, setImageData] = useState({
        image: '',
        visible: false
    })
    const [searchParams, setSearchParams] = useSearchParams();

    //地址选择后初始化
    const initFromAddress = () => {
        const addressId = searchParams.get('addressId');
        const activeId = searchParams.get('activityId');
        const cartIds = searchParams.get('cartIds');
        if (addressId && cartIds && activeId) {
            //回填选择地址前已选择商品
            changeCheckGroup(cartIds.split(',').map(id => parseInt(id)), parseInt(activeId));
            //打开地址选择弹窗
            chooseAddressRef.current.open({ deliveryType:'1', addressId });
        }
    }

    useEffect(() => {
        getCart();
    }, []);

    // 防抖处理的加减逻辑
    const handleAddOrReduce = useCallback(
        async (item, activityId, type) => {
            const goodsId = item.id;
            setLoadingMap((prev) => ({ ...prev, [goodsId]: true }));
            try {
                const nextCount = type === "add" ? item.count + 1 : item.count - 1;
                const res = await cartApi.cart_update_count({
                    id: goodsId,
                    count: nextCount,
                });

                if (res.data === true) {
                    const dataCopy = cartData.map((actItem) =>
                        actItem.activityId === activityId
                            ? {
                                ...actItem,
                                items: actItem.items.map((i) =>
                                    i.id === goodsId ? { ...i, count: nextCount } : i
                                ),
                            }
                            : actItem
                    );
                    setCartData(dataCopy);
                } else {
                    Toast.show({
                        content: res.msg,
                        position: 'top'
                    })
                }
            } catch (error) {
                console.error(`商品${type === "add" ? "增加" : "减少"}失败：`, error);
            } finally {
                setLoadingMap((prev) => ({ ...prev, [goodsId]: false }));
            }
        },
        [cartData]
    );

    const debouncedAddOrReduce = useCallback(
        debounce(handleAddOrReduce, 300, {
            leading: false,
            trailing: true,
        }),
        [handleAddOrReduce]
    );

    useEffect(() => {
        return () => {
            debouncedAddOrReduce.cancel();
        };
    }, [debouncedAddOrReduce]);

    const changeCheckGroup = (selectedValues, currentActId) => {
        const hasSelections = selectedValues.length > 0;
        setGoodsIds(selectedValues);
        setCurActId(hasSelections ? currentActId : 0);
        const updatedData = cartData.map((item) => ({
            ...item,
            disabled: hasSelections && item.activityId !== currentActId,
        }));
        setCartData(updatedData);
    };

    // 获取购物车
    const getCart = async () => {
        try {
            let res = await cartApi.cart_list();
            setCartData(res.data.validList);
            // 首次加载完成，标记isFirstLoad为false
            if (isFirstLoad) {
                setIsFirstLoad(false);
            }
        } catch (error) {
            console.error("获取购物车失败：", error);
        }
    };

    // 只在isFirstLoad变为false且initExecuted为false时执行一次
    useEffect(() => {
        // 只有当：
        // 1. 首次加载完成（isFirstLoad为false）
        // 2. 初始化逻辑尚未执行（initExecuted为false）
        // 3. 购物车数据已加载（cartData有内容）
        if (!isFirstLoad && !initExecuted && cartData.length > 0) {
            initFromAddress();
            setInitExecuted(true); // 执行后立即标记为已执行，避免再次触发
        }
    }, [isFirstLoad, initExecuted, cartData]); // 依赖这三个状态


    // 打开移除商品弹窗
    const openRemoveDialog = (id) => {
        setRemoveData({
            id: id,
            dialogVisible: true,
            loading: false
        })
    }

    // 移除商品
    const removeProduct = async () => {
        setRemoveData({ ...removeData, loading: true })
        try {
            let res = await cartApi.cart_deletet({ ids: removeData.id })
            getCart();
        } finally {
            setRemoveData({ ...removeData, loading: false, dialogVisible: false })
        }
    }



    // 计算总价
    useEffect(() => {
        if (!curActId || goodsIds.length === 0) {
            setTotalPrice(0);
            return;
        }

        //设置活动自提信息
        console.log('curActId', curActId)
        let curData = cartData.find(item => item.activityId == curActId)
        if (curData.pickupStation) {
            setPickUpStation(curData.pickupStation)
        }

        const currentActivity = cartData.find((act) => act.activityId === curActId);
        if (!currentActivity) {
            setTotalPrice(0);
            return;
        }
        const total = currentActivity.items.reduce((sum, item) => {
            if (goodsIds.includes(item.id)) {
                return sum + item.productMainRespVO.innerPrice * item.count;
            }
            return sum;
        }, 0);
        setTotalPrice(total);


    }, [cartData, goodsIds, curActId]);

    return (
        <div className="shop-car-warp">
            <div className="shopcar-title">购物车</div>

            {
                cartData.length === 0 ? <EmptyBlock /> :
                    cartData.map((actItem) => (
                        <Card className="card-warp" title={actItem.activityName} key={actItem.activityId} style={{ marginTop: "10px" }} >
                            <Checkbox.Group disabled={actItem.disabled} value={goodsIds} onChange={(v) => changeCheckGroup(v, actItem.activityId)} style={{ width: "100%" }}>
                                {actItem.items.map((item) => {
                                    const isLoading = loadingMap[item.id] || false;

                                    return (
                                        <Checkbox key={item.id} value={item.id} style={{ "--icon-size": "16px", borderBottom: "1px solid #eee" }} >
                                            <div style={{ display: "flex", margin: "10px", alignItems: "center" }}>
                                                <Image
                                                    onClick={(e) => { e.preventDefault(); setImageData({ image: item.productMainRespVO.productPicAddr, visible: true }) }}
                                                    src={item.productMainRespVO.productPicAddr}
                                                    width={60} height={60} style={{ borderRadius: "5px" }}
                                                />
                                                <div className="good-desc">
                                                    <div className="s1 product-name" >{item.productMainRespVO.productName}</div>
                                                    <div>
                                                        <Tag color="primary" fill="outline"> 效期：{item.productMainRespVO.expireTime}</Tag>
                                                        <Tag color="primary" fill="outline" style={{ marginLeft: "10px" }}>
                                                            限购：{item.productMainRespVO.minimumBuyQuantity}-
                                                            {item.productMainRespVO.limitBuyQuantity}
                                                        </Tag>
                                                    </div>
                                                    <div className="name-warp">
                                                        <span style={{ marginRight: "15px", color: "#409eff", fontSize: "14px" }} > ￥{item.productMainRespVO.innerPrice}</span>
                                                        <div style={{ display: "flex", alignItems: "center", justifyContent: "flex-end" }}>
                                                            <div style={{ display: "flex", alignItems: "center" }} >
                                                                <Button
                                                                    className="m-c" size="mini" style={{ width: '40px' }} onClick={() => debouncedAddOrReduce(item, actItem.activityId, "reduce")}
                                                                    disabled={isLoading || (item.productMainRespVO.minimumBuyQuantity && item.count <= item.productMainRespVO.minimumBuyQuantity) || actItem.disabled}
                                                                    loading={isLoading}
                                                                > 减 </Button>

                                                                <Button className="m-c" size="mini"> {item.count}</Button>

                                                                <Button className="m-c" size="mini" style={{ width: '40px' }} loading={isLoading}
                                                                    onClick={() => debouncedAddOrReduce(item, actItem.activityId, "add")}
                                                                    disabled={isLoading || (item.productMainRespVO.limitBuyQuantity && item.count >= item.productMainRespVO.limitBuyQuantity) || actItem.disabled}
                                                                > 加  </Button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <Button className="remove" size="mini" disabled={actItem.disabled} fill='outline' onClick={() => { openRemoveDialog(item.id) }}>
                                                        移除
                                                    </Button>
                                                </div>
                                            </div>
                                        </Checkbox>
                                    );
                                })}
                            </Checkbox.Group>
                            <Checkbox className="all-select" onChange={(selected) => {
                                if (selected) {
                                    const allIds = actItem.items.map(i => i.id);
                                    changeCheckGroup(allIds, actItem.activityId);
                                } else {
                                    changeCheckGroup([], 0);
                                }
                            }} style={{ '--icon-size': '16px', '--font-size': '16px' }}>全选</Checkbox>
                        </Card>
                    ))
            }

            <div className="jsuan-warp">
                <div>  合 计 ： <span style={{ color: "#e74c3c", fontSize: "20px" }}>  {totalPrice.toFixed(2)} </span> </div>
                <Button className="jiesuan" color="success" size="small" onClick={() => { chooseAddressRef.current.open() }} disabled={totalPrice === 0}> 结 算 </Button>
                <ChooseAddress
                    ref={chooseAddressRef}
                    cartIds={goodsIds}
                    activityId={curActId}
                    pickUpStation={pickUpStation}
                    loading={loadingCreate}
                />
                <Modal visible={removeData.dialogVisible}
                    content={
                        <div>
                            <div style={{ textAlign: 'center', fontSize: '18px' }}>确认删除吗？</div>
                            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '20px' }}>
                                <Button style={{ width: '48%' }} onClick={() => { setRemoveData({ ...removeData, dialogVisible: false }) }}>取消</Button>
                                <Button style={{ width: '48%' }} onClick={removeProduct} color='primary' loading={removeData.loading}>确认</Button>
                            </div>
                        </div>
                    }
                />
                <ImageViewer image={imageData.image} visible={imageData.visible} onClose={() => { setImageData({ image: '', visible: false }) }} />
            </div>
        </div>
    );
}
